//
//  serial.c
//  usb2wireless
//
//  Created by alivehex on 14-9-24.
//
//
#include <string.h>

#include "uart.h"
#include "crc7.h"
#include "serial.h"
#include "hardware.h"

#define SERIAL_NUMBER_START_ADDR	0
#define BOOT_MODE_MARK_ADDR			128

// 1 byte RF-Channel
// 5 bytes PRX-Address
int readSerialNumber(char buffer[6]) {
	unsigned char serial[7];
	unsigned char crc;
	int i;
	
	eepromRead((char *)serial, SERIAL_NUMBER_START_ADDR, sizeof(serial));
	
	crc = crc7(0, (const unsigned char *)serial, 6);
	
	if (crc != serial[6]) {
		uart1_puts("serial number crc error, use default\r\n");
		// kprintf("exp[%x] got[%x], use default\r\n", crc, serial[6]);
		buffer[0] = 2;
		memset(&buffer[1], 0xE7, 5);
	}
	else
	{
		kprintf("{");
		memcpy(buffer, serial, 6);
		for(i = 0; i < 6; i ++)
		{
			kprintf("%02x", serial[i] & 0xff);
		}
		kprintf("} ");
	}
	
	return 0;
}

int writeSerialNumber(char buffer[6]) {
	char serial[7];
	
	memcpy(serial, buffer, 6);
	serial[6] = (unsigned char)crc7(0, (const unsigned char *)buffer, 6);
	
	eepromWrite(serial, SERIAL_NUMBER_START_ADDR, sizeof(serial));
	return 0;
}

int eepromRead(char *buffer, int address, int len) {
	
	while (len --)
	{
		/* Wait for completion of previous write */
		while(EECR & (1<<EEWE));
		/* Set up address register */
		EEAR = address ++;
		/* Start eeprom read by writing EERE */
		EECR |= (1<<EERE);
		/* Return data from data register */
		*buffer ++ = EEDR;
	}
	return 0;
}

int eepromWrite(const char *buffer, int address, int len) {
	while (len --)
	{
		/* Wait for completion of previous write */
		while(EECR & (1<<EEWE));
		/* Set up address and data registers */
		EEAR = address ++;
		EEDR = *buffer ++;
		/* Write logical one to EEMWE */
		EECR |= (1<<EEMWE);
		/* Start eeprom write by setting EEWE */
		EECR |= (1<<EEWE);
	}
	return 0;
}


